# coding: utf-8
from datetime import datetime
from pathlib import Path

from PySide6.QtCore import QThread, Signal, QThreadPool

from ..setting import TEMP_DIR
from ..utils import tts_run_communicate


class TTSThread(QThread):
    error = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.text = ''
        self.voice = ''
        self.rate = 0
        self.volume = 0
        self.pitch = 0

    def run(self):
        try:
            print('开始合成, 请稍候...')
            save_path = TEMP_DIR / datetime.now().strftime('%Y%m%d%H%M%S.mp3')
            tts_run_communicate(
                self.text,
                self.voice,
                rate=self.rate,
                volume=self.volume,
                pitch=self.pitch,
                save_path=save_path,
            )
            print('合成完成, 临时保存路径:', save_path)
        except Exception as e:
            print(e)
            self.error.emit(str(e))

    def setData(self, text, voice, rate, volume, pitch):
        self.text = text
        self.voice = voice
        self.rate = rate
        self.volume = volume
        self.pitch = pitch


class BatchTTSThread(QThread):
    error = Signal(str)
    msg = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.files = []
        self.voice = ''
        self.rate = 0
        self.volume = 0
        self.pitch = 0
        self.save_dir = ''
        self.finished_count = 0

        self.pool = QThreadPool(self)
        self.pool.setMaxThreadCount(4)

    def setMaxThreadCount(self, maxThreadCount: int) -> None:
        self.pool.setMaxThreadCount(maxThreadCount)

    def run(self):
        try:
            for file in self.files:
                self.pool.start(
                    lambda f=file: self.run_communicate(
                        Path(f)
                    )
                )
            self.pool.waitForDone()
        except Exception as e:
            self.error.emit(e)
            print(e)
        print('批量合成完成')

    def run_communicate(self, file: Path):
        with open(file, 'r', encoding='utf-8') as f:
            text = f.read()
        print(f'开始合成: {file}')
        try:
            save_path = Path(self.save_dir) / f'{file.stem}.mp3'
            if save_path.exists():
                print(f'文件已存在: {save_path}')
                self.finished_count += 1
                return
            tts_run_communicate(
                text,
                self.voice,
                rate=self.rate,
                volume=self.volume,
                pitch=self.pitch,
                save_path=save_path
            )
            print(f'合成完成: {file}')
            self.finished_count += 1
        except Exception as e:
            self.error.emit(e)
            print(e)
        self.msg.emit(f'已完成{self.finished_count}/{len(self.files)}')

    def setParams(self, files: list, voice: str, rate: int, volume: int, pitch: int, save_dir: str):
        self.files = files
        self.voice = voice
        self.rate = rate
        self.volume = volume
        self.pitch = pitch
        self.save_dir = save_dir
        if not self.isRunning():
            self.start()

    def terminate(self):
        self.pool.clear()
        super().terminate()